let app = getApp();
Page({
  data: {
    iscart: false,
    cart: [], //数据  
    count: 1,
    total: 0,
    showtotal: 0,   //总金额  
    goodsCount: 0, //数量  
    image: [],
    slide: "",
    all_check: "",
    product_id: [], //购物车id
    goodsNum: [], //购物车id
    is_show_time: 1,
	statusBarHeight: app.globalData.statusBarHeight,
	productId: app.globalData.productId,
  },

  onShow: function () {
   
    new app.ToastPannel();
    var k = wx.getStorageSync('key');
    var u = wx.getStorageSync('u');
    var that = this
    var a = []
    var goods_count_num = []
    
    if (k) {
      wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=cart&typ=json',
        method: 'GET',
        data: { k: k, u: u },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {

          var arr = res.data.data.cart_list

          var total_count = 0;
          var goods_count = 0;
          // 有数据的话，就遍历数据，计算总金额 和 总数量  
          that.setData({
            is_show_time: 0
          })

          if (arr.length > 0) {
            for (var i in arr) {
              arr[i].flag = true;
              arr[i].update = false;
              arr[i].slide = "";
              var good_num = arr[i].goods;
              for (var s in good_num) {
                //计算购物车总价钱

                if (good_num[s].goods_base.promotion_type == 'groupbuy') {
                  if (good_num[s].goods_id == good_num[s].goods_base.goods_id) {
                    good_num[s].flag = false
                  }
                } else {
                  if (good_num[s].goods_base.promotion_type == 'xianshi'){
                    total_count += Number(good_num[s].goods_base.promotion_price * good_num[s].goods_num);
                  }else{
                    total_count += Number(good_num[s].goods_base.goods_price * good_num[s].goods_num);
                  }
                  
                  good_num[s].flag = true
                }

                a.push(good_num[s].cart_id)

              }
            }

            // 更新数据  
            that.setData({
              iscart: true,
              cart: arr,
              total: total_count,
              showtotal: total_count.toFixed(2),
              product_id: a,
              index: 2,
              all_check: true,

            });
          } else {
            // 更新数据  
            that.setData({
              cart: [],
              iscart: false,
              is_show_time: 0

            });
          }
        }
      })
    } else {
      that.setData({
        is_show_time: 0
      })
    }
  },
  // 自定义事件 用来接收子组件传递的数据的
   handleItemChange(e){
  		const lastProduct = app.globalData.lastProductDetail;
		if (lastProduct) {
			wx.redirectTo({
				url: '../product_detail/product_detail?goods_id=' + lastProduct.productId
			})
		} else {
			wx.switchTab({
				url: '/pages/index/index'
			})
		}
   },
  /* 减数 */
  delCount: function (e) {
    //商品id
    var that = this
   
    var k = wx.getStorageSync('key');
    var u = wx.getStorageSync('u');
    var e_id = e.target.id.substring(3);
    var arr = this.data.cart;
   
    for (var i in arr) {
      var del = arr[i].goods;
      for (var s in del) {
        var jian = del[s]
        if (jian.goods_id == e_id) {
          if (del[s].goods_base.lower_limit && jian.goods_num <= del[s].goods_base.lower_limit){
            that.show('该限时折扣商品最少需购买' + del[s].goods_base.lower_limit +'件')
            return
          }
          if (jian.goods_num <= 1) {
            return;
          } else {
            jian.goods_num -= 1
            // 加载的使用进行网络访问，把需要的数据设置到data数据对象  
            wx.request({
              url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=editCartNum&typ=json',
              method: 'GET',
              data: { k: k, u: u, cart_id: jian.cart_id, num: jian.goods_num, },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
              }
            })
            if (jian.flag == true) {
              that.data.total -= Number(jian.now_price);
            }
            that.setData({
              cart: that.data.cart,
              total: that.data.total,
              showtotal: that.data.total.toFixed(2),
              is_show_time: 0
            })
          }
        }
      }
    }
  },
  /* 加数 */
  addCount: function (e) {
    //商品id
    var that = this
    var k = wx.getStorageSync('key');
    var u = wx.getStorageSync('u');
    var e_id = e.target.id.substring(3);
    var arr = this.data.cart;
    for (var i in arr) {
      var add = arr[i].goods;
      for (var s in add) {
        var jia = add[s]
        if (jia.goods_id == e_id) {
          jia.goods_num = Number(jia.goods_num) + 1
          if (jia.goods_num > jia.goods_base.goods_stock) {
            jia.goods_num = jia.goods_base.goods_stock
            that.show("不可超过商品库存")
          } else {
            wx.request({
              url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=editCartNum&typ=json',
              method: 'GET',
              data: {
                k: k,
                u: u,
                cart_id: jia.cart_id,
                num: jia.goods_num,
              },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
              }
            })
            if (jia.flag == true) {
              that.data.total += Number(jia.now_price);
            }

            // 更新data数据对象  
            that.setData({
              cart: that.data.cart,
              total: that.data.total,
              showtotal: that.data.total.toFixed(2),
              is_show_time: 0
            })
          }
          // 加载的使用进行网络访问，把需要的数据设置到data数据对象  


        }
      }
    }
  },
  /* 删除item */
  delGoods: function (del_id) {
    var that = this
    var k = wx.getStorageSync('key');
    var u = wx.getStorageSync('u');
    var e_id = del_id;
    var arr = this.data.cart;
    for (var i in arr) {
      var delet = arr[i].goods;
      for (var s in delet) {
        var del = delet[s]
        if (del.goods_id == e_id) {
          // 加载的使用进行网络访问，把需要的数据设置到data数据对象  
          wx.request({
            url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=delCartByCid&typ=json',
            method: 'GET',
            data: { k: k, u: u, id: del.cart_id, },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
            }
          })
          that.data.cart = delet.splice(s, 1);
          if (del.flag == true) {
            that.data.total -= Number(del.goods_num * del.now_price);
          } else {
            that.data.total -= 0
          }
          var num = 0
          for (var i in arr) {
            num += arr[i].goods.length
          }
          // 商品总数量-1 
          if (num == 0) {
            var iscart = false
          } else {
            var iscart = true
          }
          // 总价钱 减去 对应项的价钱单价 
          // 更新data数据对象  
          that.setData({
            cart: arr,
            total: that.data.total,
            showtotal: that.data.total.toFixed(2),
            is_show_time: 0,
            iscart: iscart,
            nocancel: false,
          })
        }
      }
    }

  },
  //删除
  delete_goods: function (e) {
    var e_id = e.currentTarget.id.substring(3);
    this.setData({
      nocancel: true,
      del_id: e_id
    })
  },
  confirm: function () {
    var del_id = this.data.del_id
    this.delGoods(del_id)
  },
  cancel: function () {
    this.setData({
      nocancel: false,
    })
  },
  /*bindUpdate编辑*/
  bindUpdate: function (e) {
    var that = this
    var arr = that.data.cart
    for (var i in arr) {
      if (arr[i].shop_id == e.currentTarget.dataset.id) {
        arr[i].update = true;
        arr[i].slide = "slide";
      }
    }
    this.setData({
      cart: arr
    })
  },
  /*购物车输入数量*/
  goodsNum: function (e) {
    //商品id
    var that = this
    var k = wx.getStorageSync('key');
    var u = wx.getStorageSync('u');
    var e_id = e.target.dataset.id;
    var inputNum = e.detail.value
    var arr = that.data.cart;
    for (var i in arr) {
      var del = arr[i].goods;
      for (var s in del) {
        var jian = del[s]
        if (jian.goods_id == e_id) {
          if (Number(inputNum) == 0) {
            if (jian.flag == true) {
              that.data.total -= Number(jian.goods_num * jian.now_price);
              jian.goods_num = 1;
              that.data.total += Number(jian.goods_num * jian.now_price);
            } else {
              jian.goods_num = 1;
            }

            that.setData({
              cart: that.data.cart,
              total: that.data.total,
              showtotal: that.data.total.toFixed(2),
            })
            return false
          }
          if (Number(inputNum) > Number(jian.goods_base.goods_stock)) {
            if (jian.flag == true) {
              that.data.total -= Number(jian.goods_num * jian.now_price);
              jian.goods_num = jian.goods_base.goods_stock
              that.data.total += Number(jian.goods_num * jian.now_price);
            } else {
              jian.goods_num = jian.goods_base.goods_stock
            }

            that.show("不可超过商品库存")
            that.setData({
              cart: that.data.cart,
              total: that.data.total,
              showtotal: that.data.total.toFixed(2),
              is_show_time: 0
            })
          } else {
            // 加载的使用进行网络访问，把需要的数据设置到data数据对象  
            wx.request({
              url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=editCartNum&typ=json',
              method: 'GET',
              data: { k: k, u: u, cart_id: jian.cart_id, num: inputNum, },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
              }
            })

            if (jian.flag == true) {
              that.data.total -= Number(jian.goods_num * jian.now_price);
              jian.goods_num = inputNum
              that.data.total += Number(jian.goods_num * jian.now_price);

            } else {

              jian.goods_num = inputNum

            }
            that.setData({
              cart: arr,
              total: that.data.total,
              showtotal: that.data.total.toFixed(2),
              is_show_time: 0
            })
          }
        }
      }
    }
  },

  //购物车商品编辑完成
  bindcomplete: function (e) {
    var that = this
    var arr = that.data.cart
    for (var i in arr) {
      if (arr[i].shop_id == e.currentTarget.dataset.id) {
        arr[i].update = false;
        arr[i].slide = "";
      }
    }
    this.setData({
      cart: arr
    })
  },
  //全选
  bindSelectAll: function (e) {

    var total_count = 0
    var index = e.currentTarget.dataset.id;
    var arr = this.data.cart;
    var a = []
    if (index == 1) {
      for (var i in arr) {
        arr[i].flag = true
        var count = arr[i].goods;
        for (var s in count) {
          if (count[s].goods_base.promotion_type == 'groupbuy') {
            if (count[s].goods_id == count[s].goods_base.goods_id) {
              count[s].flag = false
            }
          } else {
            total_count += Number(count[s].goods_base.goods_price * count[s].goods_num);
            count[s].flag = true
            a.push(count[s].cart_id)
          }

        }
      }
      this.setData({
        total: total_count,
        showtotal: total_count.toFixed(2),
        index: 2,
        cart: arr,
        product_id: a,
      })
    } else {
      for (var i in arr) {
        arr[i].flag = false
        var count = arr[i].goods;
        for (var s in count) {
          count[s].flag = false
        }
      }
      this.setData({
        total: total_count,
        showtotal: total_count.toFixed(2),
        index: 1,
        cart: arr,
        product_id: [],
        is_show_time: 0
      })
    }



  },
  //店铺全选
  bindCheckbox: function (e) {
    var index = e.target.dataset.index
    var that = this
    var arr = that.data.cart
    var b = that.data.product_id
    if (index == false) {
      for (var i in arr) {

        var sele = arr[i].goods
        if (arr[i].shop_id == e.target.dataset.id) {
          arr[i].flag = true
          for (var s in sele) {
            if (sele[s].flag == false) {
              if (sele[s].goods_base.promotion_type == 'groupbuy') {
                if (sele[s].goods_id == sele[s].goods_base.goods_id) {
                  sele[s].flag = false
                }
              } else {
                sele[s].flag = true
                that.data.total += Number(sele[s].goods_base.goods_price * sele[s].goods_num);
                b.push(sele[s].cart_id)
              }
            }
          }

          that.setData({
            cart: arr,
            total: that.data.total,
            showtotal: that.data.total.toFixed(2),
            product_id: b,
            is_show_time: 0
          })
        }

      }

    } else {
      for (var i in arr) {
        var sele = arr[i].goods
        if (arr[i].shop_id == e.target.dataset.id) {
          arr[i].flag = false
          for (var s in sele) {
            if (sele[s].flag == true) {
              sele[s].flag = false
              that.data.total -= Number(sele[s].goods_base.goods_price * sele[s].goods_num);
            }

            var c = sele[s].cart_id
            for (var i = 0; i < b.length; i++) {
              if (c == b[i]) {
                b.splice(i, 1)
              }
            }
            that.setData({
              cart: arr,
              total: that.data.total,
              showtotal: that.data.total.toFixed(2),
              product_id: b,
              index: 1,
              all_check: "",
              is_show_time: 0
            })
          }
        }

      }

    }

  },
  //单选
  bindCheckcar: function (e) {
    var checks = e.target.dataset.checks
    var that = this
    var arr = that.data.cart
    var goods_id = e.detail.value
    var vary = that.data.product_id
    var flag = true
    console.log(e.target.dataset.id)
    if (checks == false) {
      for (var i in arr) {
        var sele = arr[i].goods
        
        for (var s in sele) {
          if (arr[i].shop_id == e.target.dataset.id) {
          if (sele[s].goods_id == goods_id) {
            if (sele[s].goods_base.promotion_type == 'groupbuy') {
              if (sele[s].goods_id == sele[s].goods_base.goods_id) {
                that.show("团购活动商品暂不支持在小程序上购买")
                sele[s].flag = false
              }
            } else {
              sele[s].flag = true
              that.data.total += Number(sele[s].goods_base.goods_price * sele[s].goods_num);
              vary.push(sele[s].cart_id)
            }
          }

        
          if (!sele[s].flag) {
            flag = false;
          }
          }
        }
        if(flag){
          if (arr[i].shop_id == e.target.dataset.id) {
          arr[i].flag = true;
          }
        }
      }
      that.setData({
        cart: arr,
        total: that.data.total,
        showtotal: that.data.total.toFixed(2),
        product_id: vary,
        is_show_time: 0
      })
    } else {
      for (var i in arr) {

        var sele = arr[i].goods
        for (var s in sele) {
          if (sele[s].goods_id == e.currentTarget.dataset.num) {
            arr[i].flag = false
            sele[s].flag = false
            that.data.total -= Number(sele[s].goods_base.goods_price * sele[s].goods_num);
            var c = sele[s].cart_id
            for (var i = 0; i < vary.length; i++) {
              if (c == vary[i]) {
                vary.splice(i, 1)
              }
            }
          }
        }
      }
      that.setData({
        cart: arr,
        total: that.data.total,
        showtotal: that.data.total.toFixed(2),
        product_id: vary,
        index: 1,
        all_check: "",
        is_show_time: 0
      })
    }

  },
  //跳转至支付页面
  addOrder: function (e) {
    var that = this
    var arr = e.currentTarget.dataset.vary
    if (arr.length == 0) {
      that.show('请选择要结算的商品');
    } else {
      wx.navigateTo({
        url: '../buy_step1/buy_step1?product_id=' + arr
      })
    }
  },
  //下拉刷新
  onPullDownRefresh: function () {
    var that = this
    wx.showToast({
      title: '加载中',//提示信息
      icon: 'loading',//成功显示图标
      duration: 2000//时间
    })
    wx.stopPullDownRefresh()
    that.onShow()
  },

})  